<?php
/**
 * Created by PhpStorm.
 * User: gsheng
 * Date: 2019/5/23
 * Time: 11:46 PM
 */

namespace app\index\controller;


header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId, Access-Token, X-Token");

class Article extends Base
{


    /**
     *  推荐产品
     *
     */

    public function cmdList()
    {
        $res = db('command')->where('id', '>', 0)->select();
        return json($res);
    }

    /**
     *  获取文章
     */
    public function getCategory()
    {
        $res = model('article')->where('id', '>', '1')->order('id', 'desc')->limit(5)->select();
        return getJson('20001', '成功', $res);
    }

    /**
     * 添加文章
     * @params
     * title: 标题
     * desc: 描述
     * content: 正文
     */
    public function addArticle()
    {
        $data = input('param.');
        $post_data = [
            'title' => $data['title'],
            'desc' => $data['desc'],
            'content' => $data['contents']
        ];
        if ($post_data) {
            $res = model('article')->data($post_data)->save();
            return getJson('10000', '添加文章成功', ($res));
        } else {
            return '登录异常,请重新登录';
        }
    }

    /**
     * 修改文章
     *
     */
    public function editArticle($id)
    {
            $post = input('param.');
            if ($post) {
                $condition = [
                    'id' => $id
                ];
                $datas = [
                    'title' => $post['title'],
                    'desc' => $post['desc'],
                    'content' => $post['contents']
                ];
                $data = db('article')->where($condition)->update($datas);
                return $data;
            } else {
                return json('没有修改内容');
            }

    }

    /**
     *  进入指定id 的文章
     */
    public function getArticleById($id)
    {
        $data = model('article')->where('id', $id)->find();
        return json($data);
    }

    /**
     * 删除文章
     */
    public function delArticle($id)
    {
        if ($id) {
            $data = db('article')->where('id', $id)->delete();
            return getJson('30001', '删除成功', $data);
        } else {
            return json('ID参数出错，请刷新重试');
        }
    }

    /**
     * 查询文章
     *
     */
    public function searchArticle()
    {
        $data = input('param.');
        if ($data) {
            $result = model('article')->where('title', 'like', '%' . $data['data'] . "%")->select();
            return json($result);
        }
    }
}